var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');

var index = require('./routes/index');
var users = require('./routes/users');
var wx = require('./routes/wx');
var agent = require('./routes/agent');
var wx_play = require('./routes/wx_play');
var downApp = require('./routes/download_app');

const config = require('./config');
const wxapi = require('./wxapi');

const app = express();

// 异常捕获
process.on('uncaughtException', function (e) {
  console.log(e);
});

if (config.wxAccessToken) {
  wxapi.init();
}

// 设置跨域访问
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', "*");
  res.header('Access-Control-Allow-Headers', "X-Requested-With,Content-Type");
  res.header('Access-Control-Allow-Methods', "POST,GET,OPTIONS");
  res.header('X-Powered-By', ' 3.2.1');
  //res.header('Content-Type', "application/json;charset=utf-8");
  //res.header('Content-Type', 'text/html');
  if(req.method=="OPTIONS") res.sendStatus(200);
  else next();
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// session
app.use(session({
  secret: 'keyboard cat',
  cookie: { maxAge: 1000 * 60 * 30 },
  resave: true,
  saveUninitialized: true,
}));

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);
app.use('/wx', wx);
app.use('/wx_play', wx_play);
app.use('/download_app', downApp);
app.use('/agent', agent)

app.get('/logout', function(req, res) {
  req.session = null;
  res.redirect('/');
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  let err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // 获取用户IP和User Agent
  let hostAddr = req.headers['x-forwarded_for'] || req.connection.remoteAddress;
  let userAgent = req.headers['user-agent'];
  let originalUrl = req.originalUrl;
  let clientInfo = `Host:${hostAddr},UA:${userAgent}`;

  let errorInfo;
  if (err.status === 404) {
    errorInfo = `* 404:${originalUrl} ${clientInfo}`;
  } else {
    errorInfo = `*** ${err.status}:${originalUrl}\nStack:${err.stack}\n${clientInfo}\n***`;
  }
  console.error(errorInfo);

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
